<template>
  <el-dialog :title="title" :visible="showDialog" @close="closeDialog">
    <el-form ref="addForm" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          autocomplete="off"
          placeholder="1-50个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          autocomplete="off"
          placeholder="1-50个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          @focus="getSimplyList"
          placeholder="请选择负责人"
          style="width:100%"
        >
          <el-option
            v-for="(item, index) in empList"
            :key="index"
            :label="item.username"
            :value="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          type="textarea"
          v-model="form.introduce"
          autocomplete="off"
          :rows="4"
          placeholder="1-300个字符"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="addClick">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDeptDetail,
  editDept
} from "@/api/departments";
import { getEmpSimplyList } from "@/api/employees";
export default {
  name: "addDept",
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    pid: {
      require: true,
      type: String,
      default: ""
    }
  },
  data() {
    // rule：源描述符中与要验证的字段名称对应的验证规则。始终为其分配一个field属性，其中包含要验证的字段的名称。
    // value：要验证的源对象属性的值。
    // callback：完成验证后调用的回调函数。它期望传递一组Error实例来指示验证失败。如果检查是同步的，您可以直接返回false或Error或Error Array。
    // source：传递给validate方法的源对象。
    // options： 其他选项。
    const changeName = async (rule, value, callback) => {
      value = value.trim();
      let res = await getDepartments();
      if (this.form.id) {
        // 编辑弹窗
        // 先找到自己的同级部门
        let list = res.data.depts.filter(item => item.pid == this.form.pid);

        list.some(item => item.name == value && item.name != this.oldForm.name)
          ? callback(new Error("已存在相同的部门名称，请重新命名！！"))
          : callback();
      } else {
        // 新增弹窗
        this.list = res.data.depts.filter(item => item.pid == this.pid);
        console.log(this.list);
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].name == value) {
            return callback(new Error("存在相同的子部门名称，请重新命名！！"));
          }
        }
        callback();
      }
    };
    const changCode = async (rule, value, callback) => {
      value = value.trim();
      let res = await getDepartments();
      let repeat;
      if (this.form.id) {
        // 编辑弹框
        repeat = res.data.depts.some(
          item => item.code === value && item.code !== this.oldForm.code
        );
      } else {
        // 新增弹框
        repeat = res.data.depts.some(item => item.code === value);
      }
      repeat
        ? callback(new Error(`部门已存在${value}部门编码，请另起编码`))
        : callback();
    };
    return {
      form: {},
      empList: [],
      rules: {
        name: [
          { required: true, message: "请输入内容", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "输入的内容长度为1-50长度",
            trigger: "blur"
          },
          {
            validator: changeName,
            trigger: "blur"
          }
        ],
        code: [
          { required: true, message: "请输入内容", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "输入的内容长度为1-50长度",
            trigger: "blur"
          },
          { validator: changCode, trigger: "blur" }
        ],
        manager: [{ required: true, trigger: "blur" }],
        introduce: [
          { required: true, message: "请输入内容", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "输入的内容长度为1-50长度",
            trigger: "blur"
          }
        ]
      },
      // 保存旧数据的name和code，用来进行校验
      oldForm: {
        name: "",
        code: ""
      }
    };
  },
  methods: {
    async getSimplyList() {
      // 获取员工简单数据列表
      let res = await getEmpSimplyList();
      this.empList = res.data;
    },
    // 确认按钮
    addClick() {
      this.$refs.addForm.validate(async v => {
        if (v) {
          if (this.form.id) {
            // 发送修改部门数据请求
            await editDept(this.form);
            // 通知用户修改成功
            this.$message.success("编辑部门成功！！");
          } else {
            // 发送请求新增部门
            await addDepartments({
              ...this.form,
              pid: this.pid
            });
            // 通知用户已新增成功
            this.$message.success("新增部门成功！！");
          }

          // 通知父组件关闭弹窗，
          this.$emit("update:showDialog", false);
          // 并重新获取数据渲染
          this.$emit("addDept");
        }
      });
    },
    // 关闭弹窗
    closeDialog() {
      this.form = {}
      this.$refs.addForm.resetFields()
      this.$emit("update:showDialog", false);
    },
    // 获取当前部门的数据
    async getNowDeptDetail(id) {
      let res = await getDeptDetail(id);
      this.form = res.data;

      this.oldForm.name = this.form.name;
      this.oldForm.code = this.form.code;
    }
  },
  computed: {
    title() {
      return this.form.id ? "编辑部门" : "新增部门";
    }
  }
};
</script>

<style lang="scss" scope>
.el-dialog {
  border-radius: 10px;
  overflow: hidden;
  .el-dialog__body {
    padding-right: 20%;
  }
}
.el-dialog__header {
  background-color: #66b1ff;
  .el-dialog__title {
    color: #fff;
  }
  .el-icon-close {
    color: #fff;
  }
}
.el-input__inner {
  width: 100%;
}
.dialog-footer {
  text-align: center;
}
</style>
